package com.shujia.spark.stream

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

object Demo6SparkOnkafka {
  def main(args: Array[String]): Unit = {

    val conf: SparkConf = new SparkConf()
      .setMaster("local[2]")
      .setAppName("wc")

    val sc = new SparkContext(conf)

    /**
      * 创建spark streaming环境
      *
      */

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    ssc.checkpoint("data/checkpoint")


    val kafkaParams: Map[String, Object] = Map[String, Object](

      "bootstrap.servers" -> "master:9092,node1:9092,node2:9092", //froker 列表
    "key.deserializer" -> classOf[StringDeserializer], //key 反序列化的列
    "value.deserializer" -> classOf[StringDeserializer],
    "group.id" -> "asdasdasd", //消费者组, 同一条数据在一个组内只被消费一次
    "auto.offset.reset" -> "latest", // 消费数据的位置（latest： 读最新数据）
    "enable.auto.commit" -> (false: java.lang.Boolean) // 是否自动提交消费偏移量

    )

    //topic
    val topics = Array("flume")

    /**
      * 创建的Dtreams是一个kv格式的，key一般没有用
      *
      */

    //链接kafka 创建DStream
    val stream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    //取出value
    var linesDS: DStream[String] = stream.map(_.value())


    linesDS.flatMap(_.split(","))
      .map((_, 1))
      .updateStateByKey((seq: Seq[Int], option: Option[Int]) => Some(seq.sum + option.getOrElse(0)))
      .print()


    ssc.start()
    ssc.awaitTermination()
    ssc.stop()


  }

}
